/**
 * Created by 61741 on 2018/1/21.
 */
var scope = "INFO";
var dt;
$(function () {
    dt = $("#mainTable").dataTable({
        fnDrawCallback: function () {
            $("img[data-src]").each(function () {
                $(this).attr("src", $(this).attr("data-src"));
            })
               loadGoodInfo();
        }
    });
    loadShop();
    loadCarouselList();
    loadGoodChosen();
    loadAllSections();
    loadArticle("", true);
    loadInfoList("INFO_TOP");
    $("#city,#goodAreaSelect,#shopAreaSelect,select[name='filterCity']").chosen({
        width: 200,
        height: 33,
        "no_results_text": "未找到对应的区域"
    });
    filterContentByCity();
})
var GOOD_CACHE = {};
var CURRENT_TARGET_GOOD_LIST;
var SHOP_GOOD_CACHE = {};
function loadShop() {
    var data = {reviewStatus: 2};
    asyncAjax({
        url: ctx + "/user/mgr/list/99?" + $.param(data).replace(/(%5D|%5B)/g, ""),//行业打牌默认配置厂商
        success: function (res) {
            console.log("res:%o", res);
            if (res["result"] == "0") {
                $.each(res["data"], function (idx, shopUser) {
                    $("#shopSelect,#goodMerchantSelector,#carouselShopSelect,#newgoodShopSelect").append("<option value='" + shopUser.id + "'>" + shopUser.companyName + "</option>");
                })
                $("#shopSelect,#goodMerchantSelector,#carouselShopSelect,#newgoodShopSelect").chosen({width: 380});
            } else {
                bootbox.alert(res["msg"]);
            }
        }
    })
}
function addCarousel() {
    var data = {
        uri: $("#uri").val() || "",
        startTime: $("#dateRange").val() ? $("#dateRange").val().split(" to ")[0] : "",
        endTime: $("#dateRange").val() ? $("#dateRange").val().split(" to ")[1] : "",
        city: $("#city").val() || "",
        type: $("#type").val() || "",
        section:$("#section").val()||"",
        sectionName:$("#section").find("option:selected").text()||""
    };

    if (data["type"] == "LINK") {
        data["typeValue"] = $("#linkInput").val()
    } else if (data["type"] == "GOOD") {
        data["typeValue"] = $("#goodSelect").val()
    } else if (data["type"] == "ARTICLE") {
        data["typeValue"] = $("#articleSelect").val()
    }

    if (isEmpty(data["uri"])) {
        bootbox.alert("轮播图片不能为空!");
        return -1;
    }
    if (isEmpty(data["startTime"]) || isEmpty(data["endTime"])) {
        bootbox.alert("请选择时间区间!");
        return -1;
    }

    if (isEmpty(data["city"])) {
        bootbox.alert("请选择投放城市!");
        return -1;
    }
    if (isEmpty(data["section"])) {
        bootbox.alert("请选择投放板块!");
        return -1;
    }
    asyncAjax({
        url: ctx + "/portal/config/carousel/" + scope + "/add?" + $.param(data).replace(/(%5D|%5B)/g, ""),
        success: function (res) {
            console.log("res:%o", res);
            if (res["result"] == "0") {
                $("#addDialog").modal("hide");
                var htmlArray = [];
                var tds = $("#carouselTmpl").tmpl(res["data"]).find("td");
                $.each(tds, function (idx, el) {
                    htmlArray.push($(el).html());
                })

                dt.fnAddData([htmlArray]);
            } else {
                bootbox.alert(res["msg"]);
            }
        }
    })
}

function loadCarouselList() {
    var data = {};
    asyncAjax({
        url: ctx + "/portal/config/carousel/list/INFO?" + $.param(data).replace(/(%5D|%5B)/g, ""),
        beforeSend: function (req) {
            dt.fnClearTable();
        },
        success: function (res) {
            console.log("res:%o", res);
            if (res["result"] == "0") {
                var dataArray = [];
                $.each(res["data"], function (idx, carousel) {
                    var htmlArray = [];
                    var tds = $("#carouselTmpl").tmpl(carousel).find("td");
                    $.each(tds, function (idx, el) {
                        htmlArray.push($(el).html());
                    })
                    dataArray.push(htmlArray);
                })
                if (dataArray.length > 0) {
                    dt.fnAddData(dataArray);
                }

            } else {
                bootbox.alert(res["msg"]);
            }
        }
    })
}

function delCarousel(cid) {
    bootbox.confirm({
        title: '提示',
        message: '确定删除此轮播图么？',
        buttons: {
            confirm: {
                label: "确定"
            },
            cancel: {
                label: '取消'
            }
        },
        callback: function (res) {
            if (res == true) {
                var data = {cid: cid};
                asyncAjax({
                    url: ctx + "/portal/config/carousel/del?" + $.param(data).replace(/(%5D|%5B)/g, ""),
                    success: function (res) {
                        console.log("res:%o", res);
                        if (res["result"] == "0") {
                            loadCarouselList();
                        } else {
                            bootbox.alert(res["msg"]);
                        }
                    }
                })
            }
        }
    })

}
function loadGoodInfo() {
    $(".target-value[data-type=\"GOOD\"]").each(function (idx, el) {
        var good = GOOD_CACHE[$(this).attr("data-value")];

        $(this).html((good ? good["goodName"] : "<code>关联商品已经失效</code>"));
    })
}
function changeValueShow() {
    var type = $("#type").val();
    switch (type) {
        case "LINK":
            $("#goodSelectBox,#articleSelectBox").hide("slow", function () {
                $("#linkInputBox").show("slow");
            });
            break;
        case "GOOD":
            $("#linkInputBox,#articleSelectBox").hide("slow", function () {
                $("#goodSelectBox").show("slow");
            });
            break;

        case "ARTICLE":
            $("#goodSelectBox,#linkInputBox").hide("slow", function () {
                $("#articleSelectBox").show("slow");
            });
            break;

    }
}

function filterContentByCity() {
    $("select[name=\"filterCity\"]").on('change', function (e, param) {
            var value = $(this).val();
            if (isEmpty(value)) {
                $(this).parents(".card").find(".good-item,.shop-item").show();
                return -1;
            }
            $(this).parents(".card").find(".good-item,.shop-item").css("display", "none");
            $(this).parents(".card").find(".good-item[data-city=\"" + value + "\"],.shop-item[data-city=\"" + value + "\"]").show("fast");
            console.log("filter :%o ,target find:%o", value, $(this).parents(".card").find(".card-content .good-item[data-city=\"" + value + "\"],.shop-item[data-city=\"" + value + "\"]"));
        }
    )
}

function loadArticle(pagetype, isFillData) {
    var data = {
        type: 1,
        uuid: 0
    };
    asyncAjax({
        url: ctx + "/article/getArticleList?" + $.param(data).replace(/(%5D|%5B)/g, ""),
        beforeSend: function (req) {
            $("#pagetype").val('');
            $("#articleSelect").html('');
        },
        success: function (res) {
            console.log("res:%o", res);
            if (res["result"] == "0") {
                if (!isEmpty(res["data"])) {
                    $.each(res["data"], function (idx, item) {
                        $("#articleSelect").append("<option value=\"" + item["id"] + "\">" + item["main_title"] + "</option>");
                    })

                    $("#articleSelect").chosen({width: 240});
                } else {
                    bootbox.confirm({
                        title: '温馨提示',
                        message: '系统没有资讯数据，如果需要配置资讯请先前往《资讯管理》进行配置.点击"确定"跳转到资讯配置页面！',
                        buttons: {
                            confirm: {
                                label: '确定'
                            },
                            cancel: {
                                label: '取消'
                            }
                        },
                        callback: function (jump) {
                            if (jump) {
                                window.location.href = ctx + "/forum/article";
//                                    $(window.top.document).find('#mainFrame').attr('src',ctx + "/forum/article") ;
                            }
                        }
                    });
                }
            } else {

            }
        },
        complete: function () {
            if (!isFillData) {
                $('#articleSelectDialog').modal('show');
            }
            $("#pagetype").val(pagetype || '');
            if (pagetype == "INFO_TOP") {
                $('#picsize').html("图片大小:290px * 320px");
            }
            else if(pagetype="INFO_PIC"){
                $('#picsize').html("图片大小:395px * 250px");
            }
        }
    })
}
function doFlagArticle(action, id, city, pagetype) {
    if (action == "DELETE") {
        if (isEmpty(id)) {
            bootbox.alert("请选择要移除的文章");
            return;
        }
        bootbox.confirm({
            title: "移除文章",
            message: "确认将文章移除么?",
            buttons: {
                confirm: {label: "确定"},
                cancel: {label: "取消"}
            },
            callback: function (res) {
                if (res == true) {
                    flagArticle(action, id, city, pagetype);
                }
            }
        })
    }
    else {
        flagArticle(action, id, city, pagetype);
    }
}

function flagArticle(action, id, city, pagetype) {
    var data = {};
    if (action == "DELETE") {
        if (isEmpty(id)) {
            bootbox.alert("请选择要移除的文章");
            return;
        }
        data["articleId"] = id;
        data["area"] = "default";
        data["pageType"] = pagetype;
    } else {
        data["articleId"] = $("#articleSelect").val();
        data["area"] = "default";
        data["pageType"] = pagetype = $('#pagetype').val();
        data["img_id"] = $("#portal_img").val();
        if (isEmpty(data["img_id"])) {
            bootbox.alert("请上传图片！");
            return;
        }
    }
    if (isEmpty(data["articleId"])) {
        bootbox.alert("请选择文章！");
        return;
    }
    if (isEmpty(data["articleId"])) {
        bootbox.alert("请选择区域！");
        return;
    }

    asyncAjax({
        url: ctx + "/portal/config/info/" + action + "?" + $.param(data).replace(/(%5D|%5B)/g, ""),
        success: function (res) {
            console.log("res:%o", res);
            if (res["result"] == "0") {
                loadInfoList(pagetype);
                $("#articleSelectDialog").modal("hide");
            } else {
                bootbox.alert(res.msg);
            }
        }
    })
}

function loadInfoList(pagetype) {
    var data = {city: "default", pagetype: pagetype};
    asyncAjax({
        url: ctx + "/portal/info/list?" + $.param(data).replace(/(%5D|%5B)/g, ""),
        beforeSend: function (req) {
            $("#" + pagetype).html('<i class="fa fa-spin fa-spinner"></i>正在刷新数据...');
        },
        success: function (res) {
            console.log("res:%o", res);
            $("#" + pagetype).html("");
            if (res["result"] == "0") {
                if (!isEmpty(res["data"])) {
                    $("#articleItemTmpl").tmpl(res["data"]).appendTo($("#" + pagetype));
                }
                else {
                    $("#" + pagetype).html('<div class="alert alert-warning">该模块尚未配置任何资讯!</div>');
                }
            } else {
                bootbox.alert(res.msg);
            }
        }
    })
}

function loadAllSections() {
    var data = {status: 1};
    asyncAjax({
        url: ctx + "/forum/list?" + $.param(data).replace(/(%5D|%5B)/g, ""),
        beforesend:function (req) {
            $("#section").html('<i class="fa fa-spin fa-spinner"></i>正在刷新数据...');
        },
        success: function (res) {
            $("section").html("");
            if (res["result"] == "0") {
                if (!isEmpty(res["data"])) {
                    $.each(res["data"],function (index,section) {
                        $("#section").append('<option value=\"' + section["id"] + '\">' + section['sectionName'] + '</option>');
                    })
                }
            }
            else {
                bootbox.alert(res["msg"]);
            }
        }

    })


}

function loadGoodChosen() {
    var data = {
        status: 1,
        pageNum: 1,
        pageSize: 50000
    };
    asyncAjax({
        url: ctx + "/goodMgr/good/list?" + $.param(data).replace(/(%5D|%5B)/g, ""),
        success: function (res) {
            console.log("res:%o", res);
            $("#goodSelect,#addGoodSelect").html("");
            if (res["result"] == "0") {
                $.each(res["data"]["goods"], function (id, good) {
                    GOOD_CACHE[good["good_id"]] = good;
                    if (!isEmpty(SHOP_GOOD_CACHE[good["wx_user_id"]])) {
                        SHOP_GOOD_CACHE[good["wx_user_id"]].push(good);
                    } else {
                        SHOP_GOOD_CACHE[good["wx_user_id"]] = [good];
                    }
                    $("#goodSelect").append('<option value=\"' + good["good_id"] + '\">' + good['goodName'] + '</option>')
                })
                $("#goodSelect").chosen({width: 240})
                console.log("good cache:%o", SHOP_GOOD_CACHE);
                $("#addGoodSelect").chosen({width: 380});
                loadGoodInfo();
            } else {
                bootbox.alert(res["msg"]);
            }
        }
    })
}
function showShopGood(el) {
    if ($(el).val() == "0") {
        return -1;
    }
    var target = $(el).attr("data-target");
    $("#" + target).html("<option value=\"\">正在载入</option>");
    $("#" + target).trigger("chosen:updated");

    var data = {
        shopId: $(el).val() || "",
        pageSize: 10000,
        pageNum: 1,
        status: "1"
    };
    asyncAjax({
        url: ctx + "/goodMgr/good/list?" + $.param(data).replace(/(%5D|%5B)/g, ""),
        success: function (res) {
            console.log("res:%o", res);
            if (res["result"] == "0") {
                var goods = res["data"]["goods"]
                if (isEmpty(goods)) {
                    bootbox.alert("该商店没有商品!");
                    return;
                } else {
                    $("#" + target).html("");
                    $.each(goods, function (idx, good) {
                        $("#" + target).append('<option value=\"' + good["good_id"] + '\">' + good['goodName'] + '</option>')
                    })
                    $("#" + target).trigger("chosen:updated");
                    $("#" + target).chosen();
                }
            } else {
                bootbox.alert(res.msg);
            }
        }
    })

}
